import React, { Component, createRef } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button, Image, ScrollView, RichText } from '@tarojs/components';
import './index.scss'
import { getFundExamination, getFundExaminationAnswerDetail, submitFundExamination } from '@/services/api/xiaoyiAccExam';
import { Popup, Toast } from '@antmjs/vantui';
import { askQuestion, getQuestionAnswer } from '@/services/api/common';
import { parseDate } from '@/utils/fomatter';

class XiaoYiAnswer extends Component {

    config = {
        navigationBarTitleText: ''
    }

    scrollViewRef = React.createRef(null);

    state = {
        type: 1,//type 2 : 结果页  1  答题页
        currentInex: 0,
        scrollLeft: 0,
        data: {},
        questions: [], // {'name' data}
        showPopUP: false,
        showXiaoyiPopUP: false,
        xiaoyiPopupType: 1, // 1 答案 2 名词解析
        xiaoyiCurrentAnswerxi: '', // 当前名词
        xiaoyiAnswerxi: {},// 答案提示
        xiaoyiNounCurrentNoun: '', // 当前名词
        xiaoyiNounPairMap: {}, // 所有保存了的名词以及解析
        requestCount: 0,
    }

    constructor(props) {
        super(props);
    }

    componentWillMount() {
        var preloadData: any = Taro.getCurrentInstance().preloadData
        this.requestData(preloadData)
        Taro.preload({})
    }

    componentDidMount() { }
    componentWillReceiveProps(nextProps, nextContext) { }
    componentWillUnmount() { }

    requestData(preloadData) {
        getFundExamination(preloadData['questionnaireType'], preloadData['questionNum']).then((resp) => {
            if (resp.code === 200) {
                this.setState({ data: resp.data, questions: resp.data['questions'] })
                Taro.setNavigationBarTitle({
                    title: resp.data['questionnaireName']
                })
            }
        })
    }

    onScrollEndd(e) {
        const { screenWidth } = Taro.getSystemInfoSync()
        var index = Math.round(e.detail.scrollLeft / screenWidth)
        this.setState({ currentInex: index })
    }

    onSubmitQuestions() {
        const { data, questions } = this.state
        var questionnaire_id = data['questionnaireId'];
        var questionnaire_type = data['questionnaireType'];
        var answer_value_str = '';
        for (let index = 0; index < questions.length; index++) {
            const element = questions[index];
            if (element['answer'] === undefined) {
                Toast.show(`你还没有作答完，无法提交！`)
                return
            }
            answer_value_str = answer_value_str + element['questionId'] + ',' + element['answer']['optValue'] + ';'
        }

        /**
         * 提交
         */
        submitFundExamination(questionnaire_id, answer_value_str, questionnaire_type).then((resp) => {
            if (resp.code === 200) {
                Taro.redirectTo({ url: '/xiaoyiAccExam/result/index' })
            }
        })

    }

    selectQuestionOption(option_value, question) {
        if (question['answer'] !== undefined) {
            return
        }
        question['answer'] = option_value;
        const { questions } = this.state
        for (let index = 0; index < questions.length; index++) {
            var element = questions[index];
            if (element.questionId === question.questionId) {
                element = question;
            }
        }
        this.setState({ questions: questions })
        if (option_value['optScore'] > 0) {
            this.nextPage()
        }
    }

    /**
     * 下一页
     */
    nextPage() {
        var { currentInex, } = this.state
        const { screenWidth } = Taro.getSystemInfoSync()
        currentInex = currentInex + 1;
        console.log(this.scrollViewRef);
        // 没有效果
        // this.scrollViewRef.current.scrollTo({
        //     scrollLeft: screenWidth*currentInex,
        //     behavior: 'smooth'
        // })
        this.setState({ scrollLeft: screenWidth * currentInex, })
    }

    gotoIndexPage(index) {
        const { screenWidth } = Taro.getSystemInfoSync()
        console.log(this.scrollViewRef);
        // 没有效果
        // this.scrollViewRef.current.scrollTo({
        //     scrollLeft: screenWidth*currentInex,
        //     behavior: 'smooth'
        // })
        this.setState({ scrollLeft: screenWidth * index, showPopUP: false })
    }

    onClose() {
        this.setState({ showPopUP: false })
    }

    showQuestionPopup() {
        this.setState({ showPopUP: true })
    }

    onXiaoyiClose() {
        this.setState({ showXiaoyiPopUP: false })
    }


    timeBox;

    /**
     * xiao'yi
     */
    xiaoYiAnswertips() {
        const fromats = [
            '请详细解析下题：',
            '请从题干分析，选项分析，最终答案，三部分，详细解析下题：',
            '请从最终答案，知识考点，详细分析，三部分，解析下题：'
        ];
        var fromat = fromats[Math.floor(Math.random() * fromats.length)];
        const { currentInex, questions, xiaoyiAnswerxi } = this.state

        this.setState({
            requestCount: 0
        })
        var question = questions[currentInex]
        if (xiaoyiAnswerxi[question['questionId']] !== undefined) {
            this.setState({ xiaoyiCurrentAnswerxi: xiaoyiAnswerxi[question['questionId']],showXiaoyiPopUP: true,xiaoyiPopupType:1 })
            return
        }

        var tempprompt = fromat + question['questionContent'];
        var currentDate = new Date();  // 当前日期
        var requestId = 'ydt' + currentDate.getTime() + 'tx'
        askQuestion(tempprompt, requestId).then((resp) => {
            if (resp.code === 200) {
                this.setState({ showXiaoyiPopUP: true,xiaoyiPopupType:1 })
                this.timeBox = setInterval(() => {
                    console.log(this.timeBox);
                    const { requestCount, } = this.state
                    if (requestCount > 10) {
                        clearTimeout(this.timeBox);
                        Toast.show('人类的问题太多了！我需要休息一下再回复您');
                        return
                    }
                    var map = JSON.parse(resp.data)
                    this.requestQuestionAnswer(map.data)
                    this.setState({
                        requestCount: requestCount + 1
                    })
                }, 2000);
            }
        })

    }

    /**
     * 
     * @param requestId 
     * @returns 
     */
    requestQuestionAnswer(requestId) {
        const { currentInex, questions, xiaoyiAnswerxi } = this.state

        var question = questions[currentInex]
        getQuestionAnswer(requestId).then((resp) => {
            console.log(resp.data)
            
            if (resp.code === 200) {
                //字符串 转 map
                var map = JSON.parse(resp.data)
                console.log(map)

                if (map.code === 200) {
                    if (map['msg'] === '人类的问题太多了！' || map['msg'] === '人类的问题太多了！我需要休息一下再回复您') { } else {
                        console.log('我在哪里')
                        clearTimeout(this.timeBox);
                        xiaoyiAnswerxi[question['questionId']] = map['msg']
                        this.setState({ showXiaoyiPopUP: true, xiaoyiAnswerxi: xiaoyiAnswerxi, xiaoyiCurrentAnswerxi: resp.data['msg'],xiaoyiPopupType:1 })
                    }
                } else {
                }
            } else {

            }
        })
    }

    

    handleSpanClick(keyword) {
        console.log(keyword)
        const { xiaoyiNounPairMap } = this.state

        this.setState({
            requestCount: 0
        })
        if ( xiaoyiNounPairMap[keyword] !== undefined) {
            this.setState({xiaoyiNounCurrentNoun:keyword,showXiaoyiPopUP: true,xiaoyiPopupType:2 })
            return
        }

        var tempprompt = keyword;
        var currentDate = new Date();  // 当前日期
        var requestId = 'ydt' + currentDate.getTime() + 'tx'
        askQuestion(tempprompt, requestId).then((resp) => {
            if (resp.code === 200) {
                this.setState({ showXiaoyiPopUP: true, xiaoyiPopupType:2,xiaoyiNounCurrentNoun:keyword,})
                this.timeBox = setInterval(() => {
                    console.log(this.timeBox);
                    const { requestCount, } = this.state
                    console.log(requestCount);
                    if (requestCount > 10) {
                        clearTimeout(this.timeBox);
                        Toast.show('人类的问题太多了！我需要休息一下再回复您');
                        return
                    }
                    var map = JSON.parse(resp.data)
                    this.requestKeywordsAnswer(keyword,map.data)
                    this.setState({
                        requestCount: requestCount + 1
                    })
                }, 2000);
            }
        })

    }

    /**
     * 
     * @param requestId 
     * @returns 
     */
    requestKeywordsAnswer(keyword,requestId) {
        const { xiaoyiNounPairMap } = this.state

        getQuestionAnswer(requestId).then((resp) => {
            console.log(resp.data)
            if (resp.code === 200) {
                console.log("======")
                //字符串 转 map
                var map = JSON.parse(resp.data)
                console.log(map)

                if (map.code === 200) {
                    if (map['msg'] === '人类的问题太多了！' || map['msg'] === '人类的问题太多了！我需要休息一下再回复您') { } else {
                        console.log('我在哪里')
                        clearTimeout(this.timeBox);
                        xiaoyiNounPairMap[keyword] = map['msg']
                        this.setState({ showXiaoyiPopUP: true, xiaoyiNounCurrentNoun: keyword, xiaoyiNounPairMap: xiaoyiNounPairMap,xiaoyiPopupType:2})
                    }
                } else {

                }
            } else {

            }
        })
    }

    render() {
        const { currentInex, questions, scrollLeft, showPopUP, showXiaoyiPopUP, xiaoyiCurrentAnswerxi, xiaoyiNounCurrentNoun, xiaoyiNounPairMap, xiaoyiPopupType, requestCount } = this.state

        return (
            <View className='page'>
                <View className='head'>
                    <View className='heade-type'>单选题</View>
                    <View className='question-card' onClick={this.showQuestionPopup.bind(this)}>
                        <Image src={require('@/assets/icons/mine/xiaoyi_answer_sheet.svg')}></Image>
                        <Text className='question-num'>{currentInex + 1}</Text>
                        <Text>{`/${questions.length}`}</Text>
                    </View>
                </View>
                <ScrollView
                    ref={this.scrollViewRef}
                    className='scrollview'
                    scrollX
                    scrollY
                    scrollWithAnimation
                    scrollLeft={scrollLeft}
                    pagingEnabled
                    enhanced
                    enableFlex
                    onScroll={this.onScrollEndd.bind(this)}
                // style={scrollStyle}
                >
                    {
                        questions.map((item, index) => {
                            var sureOptions = item['options'].find((optionsItem, index) => {
                                return optionsItem['optScore'] > 0
                            })

                            // item['keywords'] = '基金;基金公司;银行'
                            // 使用正则表达式匹配文本并将匹配到的部分包裹在span标签中，并添加样式
                            var keywords = item['keywords'].split(';')
                            const formattedText = item['questionContent'].replace(
                                new RegExp(`(${keywords.join('|')})`, 'gi'),
                                '&;&$1&;&'
                            );
                            // 将符合关键词的部分替换为自定义组件
                            const text = formattedText.split('&;&')
                            // console.log(text)
                            const replacedText = text.map((word, index) => {
                                if (keywords.includes(word)) {
                                    return <View className="title-highlight" data-text="$1" onClick={(e) => this.handleSpanClick(word)}>{word}</View>
                                }
                                return <Text key={index}>{word} </Text>
                            })
                            // console.log(replacedText);

                            return <View className='question'>
                                <View className='question-item'>
                                    {/* <RichText className='question-title'
                                        nodes={replacedText} space='nbsp'></RichText> */}
                                    <View className='question-title'>
                                        {replacedText}
                                    </View>
                                    <View className='question-option'>
                                        {
                                            (item['options']).map((optionsItem, index) => {
                                                var isSure = 0; // 0 初始  1 正确  2错误
                                                if (item['answer'] !== undefined) {
                                                    console.log(item['answer'])
                                                    if (optionsItem['optScore'] > 0) {
                                                        isSure = 1;
                                                    }
                                                    if (item['answer']['optValue'] !== undefined && optionsItem['optValue'] === item['answer']['optValue'] && optionsItem['optScore'] === 0) {
                                                        isSure = 2;
                                                    }
                                                }
                                                return <View className={`question-option-item ${isSure === 1 ? 'question-option-item-sure' : (isSure === 2 ? 'question-option-item-wrong' : '')}`} onClick={(e) => this.selectQuestionOption(optionsItem, item)}>
                                                    <Text>{`${optionsItem['optValue']}.`}</Text>
                                                    <Text>{optionsItem['optContent']}</Text>
                                                </View>
                                            })
                                        }
                                    </View>
                                    {
                                        item['answer'] !== undefined ? <>
                                            <View className='question-span'></View>
                                            <View className='question-answer'>
                                                <Text className='title'>答案解析</Text>
                                                <View className='sure-answer'>{`正确答案：${sureOptions['optValue']}`}</View>
                                                <Text className='anser-analysis'>{item['textParsing']}</Text>
                                            </View>
                                        </>
                                            : null
                                    }
                                </View>
                                <View className='bottom'>
                                    <View className='bottom-head'></View>
                                    {/* <Image className='bottom-head' src={require('@/assets/images/xiaoyi_answer_bottom.png')}></Image> */}
                                    <View className='bottom-button'>
                                        <View className='button-xy' onClick={this.xiaoYiAnswertips.bind(this)}>小以AI答案提示</View>
                                        {
                                            currentInex === questions.length - 1 ?
                                                <View className='button-next' onClick={this.onSubmitQuestions.bind(this)}>提交</View>
                                                :
                                                <View className='button-next' onClick={this.nextPage.bind(this)}>下一题</View>
                                        }
                                    </View>
                                </View>
                            </View>
                        })
                    }
                </ScrollView >
                <Popup show={showPopUP} position='bottom' onClose={this.onClose.bind(this)}>
                    <View className='pop-question-num'>
                        {
                            questions.map((item, index) => {
                                var tag = ''
                                if (item['answer'] !== undefined) {
                                    if (item['answer']['optScore'] > 0) {
                                        tag = 'pop-question-num-item-sure'
                                    } else {
                                        tag = 'pop-question-num-item-wrong'
                                    }
                                }
                                return <View className={`pop-question-num-item ${tag}`} onClick={(e) => this.gotoIndexPage(index)}>{index + 1}</View>
                            })
                        }
                    </View>
                </Popup>

                <Popup show={showXiaoyiPopUP} position='bottom' onClose={this.onXiaoyiClose.bind(this)}>
                    <View className='xiaoyi-pop-up'>
                        {
                            <Text className='xiaoyi-pop-up-title'>{xiaoyiPopupType === 1 ? '小以AI答案提示' : '小以概念百科'}</Text>
                        }
                        {
                            xiaoyiPopupType === 1 ? <Text className='xiaoyi-pop-up-context'>{xiaoyiCurrentAnswerxi.length > 0 ? xiaoyiCurrentAnswerxi : (requestCount > 10 ? '人类的问题太多了！我需要休息一下再回复您' : '小以正在思考如何回答中...')}</Text> :
                                <View className='xiaoyi-pop-up-context'>
                                    <Text className='xiaoyi-pop-up-baike'>{xiaoyiNounCurrentNoun}</Text>
                                    <Text>{(xiaoyiNounPairMap[xiaoyiNounCurrentNoun] !== undefined &&  xiaoyiNounPairMap[xiaoyiNounCurrentNoun].length > 0) ? xiaoyiNounPairMap[xiaoyiNounCurrentNoun] : (requestCount > 10 ? '人类的问题太多了！我需要休息一下再回复您' : '小以正在思考如何回答中...') }</Text>
                                </View>
                        }
                        <></>
                        <View className='xiaoyi-pop-up-line'></View>
                        <Text className='xiaoyi-pop-up-desc'>此内容根据小以自动生成，答案仅供参考</Text>
                    </View>


                </Popup>
                <Toast></Toast>
            </View >
        );
    }
}



export default XiaoYiAnswer;